﻿using CommunityToolkit.Mvvm.Input;
using HandyControl.Data;
using Koala.Pro.Common;
using Koala.Pro.Common.Extension;
using Koala.Pro.Core.Models;
using Koala.Pro.Helpers;
using Koala.Pro.Services;
using Koala.Pro.ViewModels;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Wpf.Ui.Controls;

namespace Koala.Pro.Views.Pages
{
    public partial class OperationLogListPage : Page, INavigableView<OperationLogListViewModel>
    {
        public OperationLogListViewModel ViewModel { get; }

        public OperationLogListPage(OperationLogListViewModel viewModel)
        {
            ViewModel = viewModel;
            base.DataContext = this;
            InitializeComponent();
            ViewModel.GetTreeCommand.ExecuteAsync(null);
        }

        [RelayCommand]
        private async Task Add()
        {
            await Edit(null);
        }

        [RelayCommand]
        private void OpenSetting()
        {
           ViewModel.Navigate(typeof(OperationLogSettingListPage));
        }

        [RelayCommand]
        private async Task Edit(OperationLogInfo info)
        {
            //OperationLogEditPage page = App.GetService<OperationLogEditPage>();
            //if (info != null)
            //{
            //    OperationLogEditViewModel viewModel = page.ViewModel;
            //    viewModel.Item = await BLLFactory<IOperationLogService>.Instance.GetAsync(info.Id);
            //    page.ViewModel.IsEdit = false;
            //    page.ViewModel.IsReadOnly = true;
            //}
            //else
            //{
            //    page.ViewModel.Item = new OperationLogInfo();
            //    page.ViewModel.IsEdit = false;
            //}
            //page.ShowDialog();

            //if (page.ViewModel.Result?.Success == true)
            //{
            //    await ViewModel.GetData();
            //}
        }

        [RelayCommand]
        private async Task Delete(OperationLogInfo info)
        {
            await ViewModel.DeleteCommand.ExecuteAsync(info);
            await ViewModel.GetData();
        }

        [RelayCommand]
        private void Search()
        {
            ViewModel.PageDto.Company_ID = null;
            ViewModel.SearchCommand.ExecuteAsync(null);
        }

        private async void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if ((sender as System.Windows.Controls.DataGrid)?.SelectedItem is OperationLogInfo info)
            {
                await Edit(info);
            }
        }

        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!(sender is System.Windows.Controls.DataGrid { SelectedItems: var selectedItems }))
            {
                return;
            }
            if (selectedItems != null)
            {
                List<OperationLogInfo> list = new List<OperationLogInfo>();
                foreach (OperationLogInfo item in selectedItems)
                {
                    list.Add(item);
                }
                ViewModel.SelectedItems = list;
            }
            else
            {
                ViewModel.SelectedItems = null;
            }
        }

        [RelayCommand]
        private void ImportExcel()
        {
            var page = App.GetService<ImportExcelPage>();
            page.ViewModel.Items?.Clear();
            page.ViewModel.TemplateFile = "用户关键操作记录-模板.xls";
            page.OnDataSave -= ExcelData_OnDataSave;
            page.OnDataSave += ExcelData_OnDataSave;
            ViewModel.Navigate(typeof(ImportExcelPage));
        }

        private string GetRowData(DataRow row, string columnName)
        {
            string result = "";
            if (row.Table.Columns.Contains(columnName))
            {
                result = row[columnName].ToString();
            }
            return result;
        }

        private async Task<bool> ExcelData_OnDataSave(DataRow dr)
        {
            DateTime dateTime = Convert.ToDateTime("1900-01-01");
            OperationLogInfo operationLogInfo = new OperationLogInfo();
            operationLogInfo.User_ID = GetRowData(dr, "登录用户ID");
            operationLogInfo.LoginName = GetRowData(dr, "登录名");
            operationLogInfo.FullName = GetRowData(dr, "真实名称");
            operationLogInfo.Company_ID = GetRowData(dr, "所属公司ID");
            operationLogInfo.CompanyName = GetRowData(dr, "所属公司名称");
            operationLogInfo.TableName = GetRowData(dr, "操作表名称");
            operationLogInfo.OperationType = GetRowData(dr, "操作类型");
            operationLogInfo.Note = GetRowData(dr, "日志描述");
            operationLogInfo.IPAddress = GetRowData(dr, "IP地址");
            operationLogInfo.MacAddress = GetRowData(dr, "Mac地址");
            string rowData = GetRowData(dr, "创建时间");
            if (!string.IsNullOrEmpty(rowData))
            {
                if (DateTime.TryParse(rowData, out var result) && result > dateTime)
                {
                    operationLogInfo.CreateTime = result;
                }
            }
            else
            {
                operationLogInfo.CreateTime = DateTime.Now;
            }
            return await BLLFactory<IOperationLogService>.Instance.InsertAsync(operationLogInfo);
        }

        private async void deptTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (e.NewValue is RoleAndDeptTreeNode roleAndDeptTreeNode)
            {
                ViewModel.DeptTreeModel.SelectNode = roleAndDeptTreeNode;
                ViewModel.PageDto.Company_ID = roleAndDeptTreeNode.CompanyId;
                await ViewModel.GetData();
            }
        }

        private void SearchBar_OnSearchStarted(object sender, FunctionEventArgs<string> e)
        {
            ViewModel.DeptTreeModel.SearchKey = e.Info;
            if (e.Info.IsNullOrEmpty())
            {
                ViewModel.DeptTreeModel.FilteredTreeItems = ViewModel.DeptTreeModel.TreeItems;
                return;
            }
            ViewModel.DeptTreeModel.FilteredTreeItems = ViewModel.DeptTreeModel.TreeItems.FindRoleNodes((RoleAndDeptTreeNode s) => s.Name.Contains(e.Info, StringComparison.OrdinalIgnoreCase));
        }
    }
}
